// import 'package:bruno/bruno.dart';

import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_layout/base/app_data.dart';
import 'package:flutter_layout/base/route_observers.dart';
import 'package:flutter_layout/base/routes.dart';
import 'package:flutter_layout/config/storage_manager.dart';
import 'package:flutter_layout/generated/l10n.dart';
import 'package:flutter_layout/pages/splash_page.dart';
import 'package:flutter_layout/tools/print_utils.dart';
import 'package:flutter_layout/wanandroid/wanandroid_page.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:provider/provider.dart';

void main() async {
  
  // runApp(const MyApp());
  runZonedGuarded(() async {
    initMain();
  }, (Object error, StackTrace stack) {
    // myBackend.sendError(error, stack);
    stack.printError();
    // PrintUtils.printByApp(error, level: Level.error);
  });

  // runApp(MyApp2());

  // runZonedGuarded(() => runApp(const MyApp()), (Object obj, StackTrace stack) {
  //   //这里可以构建错误信息,然后上报
  // }, zoneSpecification: ZoneSpecification(
  //   print: (Zone self, ZoneDelegate parent, Zone zone, String line) {
  //     // 记录所有的打印日志
  //     parent.print(zone, "<错误信息>\n$line");
  //   },
  // ));

  // runZonedGuarded(() async {
  //   WidgetsFlutterBinding.ensureInitialized();
  //   await myErrorsHandler.initialize();
  //   FlutterError.onError = (FlutterErrorDetails details) {
  //     FlutterError.presentError(details);
  //     myErrorsHandler.onError(details);
  //     exit(1);
  //   };
  // runApp(MyApp2());
  // }, (Object error, StackTrace stack) {
  //   myErrorsHandler.onError(error, stack);
  //   exit(1);
  // });
}

void initMain() async {
  FlutterError.onError = (FlutterErrorDetails details) {
    FlutterError.presentError(details);
    // if (kReleaseMode) exit(1);
  };
  // 玩安卓初始化
  Provider.debugCheckInvalidValueType = null;
  WidgetsFlutterBinding.ensureInitialized();
  await StorageManager.init();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  //
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return const WanandroidPage();
    // return appOne();
  }

  Widget appOne() {
    // BrnInitializer.register(allThemeConfig:BrnAllThemeConfig());
    // S.of(context);
    // App.loginStatus = 0;
    WidgetsFlutterBinding.ensureInitialized();
    AppData.initData();

    ///初始化本地数据
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp, //强制竖屏
      DeviceOrientation.portraitDown
    ]);
    var locales = S.delegate.supportedLocales;

    // ScreenUtilInit( builder: () {

    // },)
    return GetMaterialApp(
      enableLog: kDebugMode,
      // initialRoute: Routes.home,
      getPages: Routes.getPages,
      // onUnknownRoute: (settings) {

      // },
      unknownRoute: Routes.unknownRoute,
      localizationsDelegates: const [
        S.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate, // Here !
        GlobalWidgetsLocalizations.delegate,
      ],
      locale: locales[1],
      supportedLocales: locales,
      fallbackLocale: locales[1], //默认语言
      localeListResolutionCallback: (locales, supportedLocales) {
        if (kDebugMode) {
          print('当前系统语言环境:$locales');
        }
        return;
      },
      navigatorObservers: [RouteObservers()],
      debugShowCheckedModeBanner: false,
      // title: "${S.of(context).string_main_title}",
      // highContrastTheme: ThemeData(
      //   primarySwatch: Colors.yellow,
      // ),
      // darkTheme: ThemeData(
      //   primarySwatch: Colors.yellow,
      // ),
      // theme: theme,
      theme: ThemeData(
        visualDensity: VisualDensity.adaptivePlatformDensity,
        primarySwatch: Colors.yellow,
        primaryColorLight: Colors.yellow,
        primaryColorDark: Colors.yellow,
      ),
      home: const SplashPage(),
      builder: (context, child) {
        ErrorWidget.builder = (FlutterErrorDetails errorDetails) {
          Widget error = SingleChildScrollView(child: Text("很抱歉，您的程序出现错误：\n${errorDetails.exceptionAsString()}"));
          if (child is Scaffold || child is Navigator) {
            error = Scaffold(body: Center(child: error));
          }
          return error;
        };
        var mediaquery = MediaQuery(

            ///设置文字大小不随系统设置改变
            data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
            child: child ?? Container());
        return mediaquery;
      },
    );
    // return ScreenUtilInit(
    //   designSize: const Size(750, 1334),
    //   builder: () => ;
    // );
  }
}

class MyApp2 extends StatelessWidget {
  const MyApp2({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage2(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage2 extends StatefulWidget {
  const MyHomePage2({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage2> createState() => _MyHomePageState2();
}

class _MyHomePageState2 extends State<MyHomePage2> {
  int _counter = 0;

  void _incrementCounter() async {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
      // getPage();
    });
    // List<Future> futures = [];
    // futures.add(WanAndroidRepository.fetchBanners());
    // futures.add(WanAndroidRepository.fetchTopArticles());
    // futures.add(WanAndroidRepository.fetchArticles(0));
    // futures.add(Future.delayed(Duration(milliseconds: 300)));

    // futures.add(fetchBanners());
    // futures.add(fetchTopArticles());
    // futures.add(fetchArticles());
    // var result = await Future.wait(futures);
    // print("---ddddd3333--");
  }

  // static Future fetchArticles() async {
  //   await Future.delayed(const Duration(seconds: 1)); //增加动效
  //   var response = await Future.sync(() => null);
  //   return response;
  // }

  // static Future fetchBanners() async {
  //   var response = await Future.sync(() => null);
  //   return response;
  // }

  // static Future fetchTopArticles() async {
  //   var response = await Future.sync(() => null);
  //   ;
  //   return response;
  // }

  void getPage({int? page}) {
    // print("page=${page}");
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
